from PySide6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QTabWidget, 
    QLabel, QComboBox, QPushButton, QGroupBox, QScrollArea
)
from PySide6.QtCore import Qt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import pandas as pd
import numpy as np
from ui.resources import Resources

class AnalysisPanel(QWidget):
    """数据分析面板"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self._data = None
        self._setup_ui()
    
    def _setup_ui(self):
        """设置UI"""
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)
        
        # 控制面板
        control_panel = QGroupBox("分析控制")
        control_layout = QHBoxLayout()
        control_panel.setLayout(control_layout)
        
        self.x_axis_combo = QComboBox()
        self.y_axis_combo = QComboBox()
        self.group_combo = QComboBox()
        
        control_layout.addWidget(QLabel("X轴:"))
        control_layout.addWidget(self.x_axis_combo, 1)
        control_layout.addWidget(QLabel("Y轴:"))
        control_layout.addWidget(self.y_axis_combo, 1)
        control_layout.addWidget(QLabel("分组:"))
        control_layout.addWidget(self.group_combo, 1)
        
        self.plot_btn = QPushButton("绘图")
        self.plot_btn.clicked.connect(self._plot_data)
        control_layout.addWidget(self.plot_btn)
        
        self.layout.addWidget(control_panel)
        
        # 分析结果标签页
        self.tab_widget = QTabWidget()
        self.layout.addWidget(self.tab_widget, 1)
        
        # 统计标签页
        self.stats_tab = QScrollArea()
        self.stats_tab.setWidgetResizable(True)
        self.stats_content = QWidget()
        self.stats_layout = QVBoxLayout()
        self.stats_content.setLayout(self.stats_layout)
        self.stats_tab.setWidget(self.stats_content)
        self.tab_widget.addTab(self.stats_tab, "统计")
        
        # 图表标签页
        self.chart_tab = QWidget()
        self.chart_layout = QVBoxLayout()
        self.chart_tab.setLayout(self.chart_layout)
        
        # Matplotlib图表
        self.figure = Figure(figsize=(8, 6), dpi=100)
        self.canvas = FigureCanvas(self.figure)
        self.chart_layout.addWidget(self.canvas)
        
        self.tab_widget.addTab(self.chart_tab, "图表")
    
    def set_data(self, data: pd.DataFrame):
        """设置数据"""
        self._data = data
        
        # 更新下拉框选项
        self._update_combos()
        
        # 自动显示统计信息
        self.show_stats()
    
    def _update_combos(self):
        """更新下拉框选项"""
        if self._data is None:
            return
        
        columns = self._data.columns.tolist()
        
        self.x_axis_combo.clear()
        self.y_axis_combo.clear()
        self.group_combo.clear()
        
        self.x_axis_combo.addItems(columns)
        self.y_axis_combo.addItems(columns)
        self.group_combo.addItems([""] + columns)
    
    def show_stats(self):
        """显示统计信息"""
        if self._data is None:
            return
        
        # 清空现有内容
        while self.stats_layout.count():
            child = self.stats_layout.takeAt(0)
            if child.widget():
                child.widget().deleteLater()
        
        # 计算描述统计
        stats = self._data.describe(include='all').T
        stats['missing'] = self._data.isnull().sum()
        stats['unique'] = self._data.nunique()
        
        # 为每列创建统计信息
        for col in self._data.columns:
            group = QGroupBox(col)
            layout = QVBoxLayout()
            group.setLayout(layout)
            
            # 数据类型
            dtype_label = QLabel(f"类型: {self._data[col].dtype}")
            layout.addWidget(dtype_label)
            
            # 基本统计
            if np.issubdtype(self._data[col].dtype, np.number):
                stats_text = (
                    f"计数: {stats.loc[col, 'count']:.0f}\n"
                    f"均值: {stats.loc[col, 'mean']:.2f}\n"
                    f"标准差: {stats.loc[col, 'std']:.2f}\n"
                    f"最小值: {stats.loc[col, 'min']:.2f}\n"
                    f"25%分位数: {stats.loc[col, '25%']:.2f}\n"
                    f"中位数: {stats.loc[col, '50%']:.2f}\n"
                    f"75%分位数: {stats.loc[col, '75%']:.2f}\n"
                    f"最大值: {stats.loc[col, 'max']:.2f}\n"
                    f"缺失值: {stats.loc[col, 'missing']}\n"
                    f"唯一值: {stats.loc[col, 'unique']}"
                )
            else:
                stats_text = (
                    f"计数: {stats.loc[col, 'count']:.0f}\n"
                    f"唯一值: {stats.loc[col, 'unique']}\n"
                    f"缺失值: {stats.loc[col, 'missing']}\n"
                    f"众数: {stats.loc[col, 'top']}\n"
                    f"众数频率: {stats.loc[col, 'freq']:.0f}"
                )
            
            stats_label = QLabel(stats_text)
            stats_label.setWordWrap(True)
            layout.addWidget(stats_label)
            
            self.stats_layout.addWidget(group)
    
    def show_chart(self):
        """显示默认图表"""
        if self._data is None:
            return
        
        self.tab_widget.setCurrentIndex(1)
        self._plot_data()
    
    def _plot_data(self):
        """绘制图表"""
        if self._data is None:
            return
        
        x_col = self.x_axis_combo.currentText()
        y_col = self.y_axis_combo.currentText() if self.y_axis_combo.currentIndex() >= 0 else None
        group_col = self.group_combo.currentText() if self.group_combo.currentIndex() > 0 else None
        
        self.figure.clear()
        ax = self.figure.add_subplot(111)
        
        if y_col is None:
            # 单变量图表
            if np.issubdtype(self._data[x_col].dtype, np.number):
                # 数值数据 - 直方图
                ax.hist(self._data[x_col].dropna(), bins=20, edgecolor='black')
                ax.set_title(f"{x_col} 分布")
                ax.set_xlabel(x_col)
                ax.set_ylabel("频数")
            else:
                # 分类数据 - 条形图
                value_counts = self._data[x_col].value_counts()
                value_counts.plot(kind='bar', ax=ax, edgecolor='black')
                ax.set_title(f"{x_col} 频数")
                ax.set_xlabel(x_col)
                ax.set_ylabel("计数")
        else:
            # 双变量图表
            if group_col:
                # 分组数据
                groups = self._data.groupby(group_col)
                for name, group in groups:
                    ax.scatter(group[x_col], group[y_col], label=name)
                ax.legend()
            else:
                # 无分组数据
                ax.scatter(self._data[x_col], self._data[y_col])
            
            ax.set_title(f"{x_col} vs {y_col}")
            ax.set_xlabel(x_col)
            ax.set_ylabel(y_col)
        
        self.figure.tight_layout()
        self.canvas.draw()